package com.ceczj.apolloapi.temp;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.MappingIterator;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.dataformat.csv.CsvMapper;
import com.fasterxml.jackson.dataformat.csv.CsvSchema;
import lombok.SneakyThrows;
import org.springframework.http.*;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;

import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;
import java.util.*;
import java.util.concurrent.*;

public class aliAI {

    public static final String MODEL = "qwen-plus";
    public static final String TOKEN = "Bearer sk-bcf26fd033f54d5f9d38153d562892fd";
    public static final String SYSTEM = "我将给你一个json数组,去遍历每一个对象把每一个字段都一定要翻译成英文返回。同时要求如果包含企业名称的信息,则设置为字段qymc的值（也要求是英文）,否则为空。返回是可直接解析json数组文本不用\n分割";
    public static final String IN = """
            C:\\Users\\29005\\Downloads\\xwechat_files\\wxid_y4j1b8u6de8l22_8385\\msg\\file\\2025-08\\%s.csv""";
    public static final String OUT = """
            C:\\Users\\29005\\Downloads\\xwechat_files\\wxid_y4j1b8u6de8l22_8385\\msg\\file\\2025-08\\%s_out.csv""";
    public static final String TEMP = """
            C:\\Users\\29005\\Downloads\\xwechat_files\\wxid_y4j1b8u6de8l22_8385\\msg\\file\\2025-08\\%s_temp.csv""";
    public static final String ERROR = """
            C:\\Users\\29005\\Downloads\\xwechat_files\\wxid_y4j1b8u6de8l22_8385\\msg\\file\\2025-08\\%s_error.csv""";

    @SneakyThrows
    public static void main(String[] argsl) throws IOException {

        String name = "ukr_importername(2)";
        extracted(IN.formatted(name),OUT.formatted(name), TEMP.formatted(name), 50);
        String name2 = "ukr_suppliername(2)";
        extracted(IN.formatted(name2),OUT.formatted(name2), TEMP.formatted(name2), 50);

        extracted(TEMP.formatted(name),OUT.formatted(name), ERROR.formatted(name), 1);
        extracted(TEMP.formatted(name2),OUT.formatted(name2), ERROR.formatted(name2), 1);
    }

    private static void extracted(String in,String out, String outError,int size) throws IOException {
        ThreadPoolExecutor pools = new ThreadPoolExecutor(
                10,
                10,
                0L,
                TimeUnit.SECONDS,
                new LinkedBlockingQueue<>(100000)
        );
        File csvFile = new File(in);
        CsvMapper csvMapper = new CsvMapper();
        ObjectMapper objectMapper = new ObjectMapper();
        List<String> strings = csvMapper.readValue(csvFile, new TypeReference<>() {
        });

        CsvSchema.Builder builder = CsvSchema.builder();
        for (String string : strings) {
            builder.addColumn(string);
        }
        builder.addColumn("qymc");
        CsvSchema schema = builder.build();

        MappingIterator<Map> it = csvMapper
                .readerFor(Map.class)
                .with(schema)
                .readValues(csvFile);

        List<Map> list = it.readAll();
        list.remove(0);

        List<CompletableFuture<Void>> futures = new ArrayList<>();

        // Process in batches of BATCH_SIZE
        for (int i = 0; i < list.size(); i += size) {
            int end = Math.min(i + size, list.size());
            List<Map> batch = list.subList(i, end);

            futures.add(CompletableFuture.runAsync(() -> {
                boolean b;
                int count = 0;
                // Send request and process response
                do {
                    // 创建请求头
                    HttpHeaders headers = new HttpHeaders();
                    headers.setContentType(MediaType.APPLICATION_JSON);
                    headers.setAccept(Collections.singletonList(MediaType.ALL));
                    headers.set("Authorization", TOKEN);
                    headers.set("Connection", "keep-alive");

                    // 创建请求体模板
                    Map<String, Object> requestBody = new HashMap<>();
                    requestBody.put("model", MODEL);

                    List<Map<String, Object>> messages = new ArrayList<>();

                    Map<String, Object> systemMessage = new HashMap<>();
                    systemMessage.put("role", "system");
                    systemMessage.put("content", SYSTEM);
                    messages.add(systemMessage);

                    Map<String, Object> userMessage = new HashMap<>();
                    userMessage.put("role", "user");
                    messages.add(userMessage);

                    requestBody.put("messages", messages);
                    // Create HTTP entity for this batch
                    try {
                        userMessage.put("content", objectMapper.writeValueAsString(batch));
                    } catch (JsonProcessingException e) {
                        throw new RuntimeException(e);
                    }
                    HttpEntity<Map<String, Object>> entity = new HttpEntity<>(requestBody, headers);
                    long l = System.currentTimeMillis();
                    b = processBatch(
                            entity,
                            objectMapper,
                            out,
                            csvMapper,
                            schema);
                    System.out.println("Processed " + end + " of " + list.size() + " items : time " + (System.currentTimeMillis() - l));
                    count++;
                } while (!b && count < 3);

                if (count == 3 && !b) {
                    Path path = Path.of(outError);
                    synchronized (aliAI.class) {
                        try (OutputStream os = Files.newOutputStream(
                                path,
                                StandardOpenOption.CREATE,
                                StandardOpenOption.APPEND
                        )) {
                            csvMapper.writer(schema).writeValue(os, batch);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }
            }, pools));

        }

        CompletableFuture.allOf(futures.toArray(new CompletableFuture[0])).join();

    }

    @SneakyThrows
    private static boolean processBatch(HttpEntity<Map<String, Object>> entity,
                                        ObjectMapper objectMapper,
                                        String out,
                                        CsvMapper csvMapper,
                                        CsvSchema csvSchema) {
        String rs = "";
        try {
            // 发送请求
            SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
            // Set connection timeout to infinite
            requestFactory.setConnectTimeout(0);
            // Set read timeout to infinite
            requestFactory.setReadTimeout(0);
            RestTemplate restTemplate = new RestTemplate(requestFactory);
            ResponseEntity<String> response = restTemplate.exchange(
                    "https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions",
                    HttpMethod.POST,
                    entity,
                    String.class
            );
            rs= response.getBody();

            if (response.getStatusCode() == HttpStatus.OK) {
                JSONObject jsonObject = new JSONObject(response.getBody());
                JSONArray contentArray = jsonObject.get("choices", JSONArray.class);
                JSONObject choices = (JSONObject) contentArray.get(0);
                JSONObject message = choices.get("message", JSONObject.class);
                String content = message.get("content").toString();
                List list = objectMapper.readValue(content, List.class);
                // 如果文件不存在，则创建；如果存在，则追加
                Path path = Path.of(out);
                synchronized (aliAI.class) {
                    try (OutputStream os = Files.newOutputStream(
                            path,
                            StandardOpenOption.CREATE,
                            StandardOpenOption.APPEND
                    )) {
                        boolean isNewFile = !Files.exists(path);
                        if (isNewFile) {
                            // 新文件：写入表头 + 数据
                            csvMapper.writer(csvSchema).writeValue(os, list);
                        } else {
                            // 已有文件：仅追加数据（不重复表头）
                            csvMapper.writer(csvSchema.withoutHeader()).writeValue(os, list);
                        }
                    }
                }
            }
            return true;
        } catch (Exception e) {
            System.out.println(rs);
            e.printStackTrace();
            // You might want to add retry logic here
        }
        return false;
    }

}